var tableManage = function() {
    var defaultContent='<button type="button" class="btn btn-info btn-xs btn_edit_role">编辑</button>&nbsp;&nbsp;<button type="button" class="btn btn-danger btn-xs btn_del_role">删除</button>';
    var typeDefault = '<button type="button" class="btn btn-info btn-xs btn_edit_type">编辑</button>&nbsp;&nbsp;<button type="button" class="btn btn-danger btn-xs btn_del_type">删除</button>';

    var _init = function() {
        var table = $('#product_table');
        table.dataTable({
            "processing": true,            
            serverSide: true,// 开启服务器模式
            "ajax": {
            	url:plist_url,
            },
            "autoWidth": true,
            "columns": [
                {
                    "data": "imgUrl",
                    "render": function(data, type, row, meta) {
                        return "<img class='center-block' src='"+data+"' alt='' />"
                    }
                },
                {"width": "20%","data": "title"},
                {"data": "typeName"},
                {
                    "data": "currentPrice",
                    "render": function(data, type, row, meta) {
                        return data/100;
                    }
                },
                {
                    "data": "memberPrice",
                    "render": function(data, type, row, meta) {
                        return data/100;
                    }
                },
                {
                    "data": "updateDate",
                    "render": function(data, type, row, meta) {
                        return moment(data).format('YYYY-MM-DD HH:mm');
                    }
                },
                {"width": "16.5%","data": "null","defaultContent": defaultContent}
            ],
            "language": {
            	url: '/public/static/assets/pages/Chinese.json'
            },
            "lengthMenu": [[20, 50, 100, 150], [20, 50, 100, 150]],
            "pageLength": 20,
            "scrollX":"",
            "destroy": false,
            "stateSave": true,
            "stateSaveParams": function (settings, data) {
                var search=data.search.search;
                if(search){
                	var arr=$.parseJSON(search);
                	for(var key in arr){
            		   $("#searchForm input[name='"+key+"']").val(arr[key]);
            		   $("#searchForm select[name='"+key+"']").val(arr[key]);
            		}
                }
            },
            "order": [
                [1, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0,2,5]
            }],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
            "fnInitComplete": function() {
            	var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象 
            }
        });   
        
        // 关闭弹框
        $(".modal").on('hidden.bs.modal', function(e) {
            $('.modal .alert').css('display', 'none'); // 隐藏提示头
            $('.modal .form-group').removeClass('has-error'); //清除错误信息
            $('.modal input[type="text"]').val(''); // 清空 input
            $('.modal input[type="checkbox"]').prop('checked', false); // 清空 input
        });
        
        // 商品修改
        table.on('click', '.btn_edit_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;
            ajaxType(_id);
        });

        //商品删除
        table.on('click', '.btn_del_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;
            var param = {'id':_id};
            var totalSales=oData_arr[0].totalSales;
            var text = $(this).data('confirm') ? $(this).data('confirm') : '是否要删除？';
            var title = $(this).data('title') ? $(this).data('title') : '删除店员';
            var confirmBtn = $(this).data('confirmbtn') ? $(this).data('confirmbtn') : '确定';
            var cancelBtn = $(this).data('cancelbtn') ? $(this).data('cancelbtn') : '取消';
            layer.confirm(
                text, // 内容
                {
                    // icon: 7,
                    // 标题
                    title: title,
                    // 按钮
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    $.ajax({
                        url : productDel_url,
                        type : 'POST',
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify(param),
                        async: false
                    }).done(function(data) {
                        if (data.code === '1') {
                            layer.msg('删除成功');
                            //table.DataTable().ajax.reload();
                            table.DataTable().draw(false);
                        } else if (data.code === '2') {
                            layer.msg(data.message);
                        }
                    });

                    layer.close(index);
                }
            );
        });

        var type_table = $('#productType_table');
        type_table.dataTable({
                "processing": true,
                "searching": false,         
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url:typeList_url,
                },
                "autoWidth": true,
                "columns": [
                    {"width": "20%","data": "name"},
                    {"width": "20%","data": "orderNo"},
                    {
                        "width": "20%",
                        "data": "createDate",
                        "render": function(data, type, row, meta) {
                            return moment(data).format('YYYY-MM-DD HH:mm');
                        }
                    },
                    {"width": "40%","data": "null","defaultContent": typeDefault}
                ],
                "language": {
                    url: '/public/static/assets/pages/Chinese.json'
                },
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "order": [
                    [1, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                    "<t>" +
                    "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                }
        });

        // 商品分类修改
        type_table.on('click', '.btn_edit_type', function(event) {
            $(this).attr("disabled","disabled");
            $(this).parents("tr").siblings("tr").find(".btn_edit_type").attr("disabled","disabled");
            $(this).parents(".modal-content").find("#addType").attr("disabled","disabled");

            var oData_arr = type_table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            //console.log(oData_arr);
            var _id = oData_arr[0].id;
            var name = oData_arr[0].name;
            var orderNo = oData_arr[0].orderNo;

            $(this).parents('.modal-body').find('table tbody:last').append(typeTemplate);
            $('#productType_table').find('[name="id"]').val(_id);
            $('#productType_table').find('[name="name"]').val(name);
            $('#productType_table').find('[name="orderNo"]').val(orderNo);
            
        });

        //商品分类保存
        type_table.on('click', '.btn_save_type', function(event) {

            var _id = $('#productType_table').find('[name="id"]').val();
            var orderNo = $('#productType_table').find('[name="orderNo"]').val();
            var name = $('#productType_table').find('[name="name"]').val();

            var param={"id":_id,"orderNo":orderNo,"name":name};
            //console.log(param);

            if (!mdTool.validate(name, 'require')) {
                // $('.ban-typelist').find('.help-block').html('请填写分类名称');
                layer.msg('请填写分类名称');
                return;
            }
            if(name.length > 12) {
                layer.msg('名称过长，最多12字符');
                return;
            }
            if (!mdTool.validate(orderNo, 'num')) {
                layer.msg('请输入正确的排序');
                return;
            } else if (orderNo.length > 10){
                layer.msg('排序长度最长为10位');
                return;
            } else {
                var _type = _id == null||_id == '' ? "post" : "put";

                $.ajax({
                    url : typeSave_url,
                    type : _type,
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                }).done(function(data) {
                    if (data.code === '1') { // 正确
                        layer.msg('保存成功');
                        //type_table.DataTable().ajax.reload();
                        type_table.DataTable().draw(false);
                        $("#addType").attr("disabled",false);
                        $('.ban-typelist').find('.help-block').html('');
                    } else if (data.code === '2') { // 错误
                        layer.msg(data.message);
                    }
                });
            }
        });

        //删除
        type_table.on('click', '.btn_del_type', function(event) {
            var oData_arr = type_table.DataTable().rows($(this).parents("tr")).data();
            var _id = oData_arr[0].id;
            param = {'id':_id};
            var text = $(this).data('confirm') ? $(this).data('confirm') : '是否要删除？';
            var title = $(this).data('title') ? $(this).data('title') : '删除店员';
            var confirmBtn = $(this).data('confirmbtn') ? $(this).data('confirmbtn') : '确定';
            var cancelBtn = $(this).data('cancelbtn') ? $(this).data('cancelbtn') : '取消';
            layer.confirm(
                text, // 内容
                {
                    // icon: 7,
                    // 标题
                    title: title,
                    // 按钮
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    $.ajax({
                        url : typeDel_url,
                        type : 'POST',
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify(param),
                        async: false
                    }).done(function(data) {
                        if (data.code === '1') {
                            layer.msg('删除成功');
                            $("#addType").attr("disabled",false);
                            //type_table.DataTable().ajax.reload();
                            type_table.DataTable().draw(false);
                        } else if (data.code === '2') {
                            layer.msg(data.message);
                        }
                    });

                    layer.close(index);
                }
            );
        });


        // 取消
        $(".ban-typelist").on('click','.btn_cancle_type',function(){
            $(this).parents("table").find(".btn_edit_type").attr("disabled",false);
            $(this).parents(".modal-content").find("#addType").attr("disabled",false);
            $(this).parent().parent().remove();
            return false;
        });

    };

    return {
        init: function() {
            _init();
        }

    };

}();


$('#doQuery').click(function(event){  //商品搜索
    var title =   $("#searchForm input[name='title']").val();
    var typeId =   $("#searchForm select[name='typeId']").val();
    var param={"title":title,"typeId":typeId};
    $('#product_table').DataTable().search(JSON.stringify(param)).draw();	  
});
   

function ajaxType(id){

	if(id){
    	window.location.href = productEdit_url+"?id="+encodeURIComponent(id);
	}else{
        if(is_tdt == 0){
            layer.alert('您还未初始化物流信息', {
                btn: ['前去设置', '取消']
                ,yes: function(index, layero){
                    window.location.href = '/admin/tenantDistributionType/index'
                }
                ,btn2: function(index, layero){
                }
            });
        }else {
            //新增商品前判断是否已创建门店
            $.ajax({
                url : checkStore,
                type : 'POST',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                async: false
            }).done(function(data) {
                if(data) {
                    window.location.href = productAdd_url;
                }else {
                    layer.alert('您还没有门店，请去添加', {
                        btn: ['前去设置', '知道了']
                        ,yes: function(index, layero){
                            window.location.href = store_add
                        }
                        ,btn2: function(index, layero){
                        }
                    });
                }
            });
        }

	}
}

function addType(){
    
    $('.ban-typelist').modal('show');   //显示分类弹出层
}

var typeTemplate = stringLines(function(){/*
    <tr >
        <td>
            <input type="text" maxlength="12" placeholder="最多12字符" name="name" class="form-control " />
        </td>
        <td>
            <input type="text" min="1" maxlength="5" placeholder="排序" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" name="orderNo" class="form-control" />
        </td>
        <td style="width:130px;">
            <input type="hidden" name="id">
            <button type="button" name="saveAdvertisement" class="btn btn-primary btn_save_type">保存</button>
            <button type="button" class="btn btn_cancle_type">取消</button>
        </td>
    </tr>
*/});

//商品分类添加行代码
$('#addType').click(function(){
    $(this).attr("disabled","disabled");
    $(this).parent().next().find('table .btn_edit_type').attr("disabled","disabled");
    $(this).parent().next().find('table tbody:last').append(typeTemplate);
});
	  
$(function() {
    tableManage.init();
});